const User = require('../../models/user')
const Article = require('../../models/article');
const user = require('../../models/user');
const userInfo = require('./userInfo');

module.exports = (req, res) => {
  var formData = JSON.parse(req.body.formData)
  // console.log(formData);
  var articleDocs={}
  Article.findById({ _id: formData.articleForm.article_id }, (err, articleDoc) => {
    articleDocs = articleDoc
    /* 
      将收藏文章的用户信息插入article_user.collect
    */
    if (formData.code === 0) {
      articleDoc.article_user.collect.push(formData.userForm)
    }
    /*
      将点赞文章的用户信息插入article_user.like
    */
    if (formData.code === 1) {
      articleDoc.article_user.like.push(formData.userForm)
    }
    Article.updateOne({ _id: formData.articleForm.article_id }, { $set: { article_user: articleDoc.article_user } }, (err, newArticleDoc) => {
      if (err) {
        res.status(500).json({
          err_code: 500,
          message: err.message
        })
      }
    })
  })
  

  User.findById({ _id: formData.userForm.user_id }, (err, userDoc) => {
    formData.articleForm.article_info = JSON.stringify(articleDocs)
    /* 
      将收藏的文章插入到user_article.collect里
    */
    if (formData.code === 0) {
      userDoc.user_article.collect.push(formData.articleForm)
    }
    // console.log(formData);
    /* 
      将文章加入到用户收藏的数据库user_article.like里
    */
    if (formData.code === 1) {
      userDoc.user_article.like.push(formData.articleForm)
    }
    User.updateOne({ _id: formData.userForm.user_id }, { $set: { user_article: userDoc.user_article } }, (err) => {
      if (err) {
        res.status(500).json({
          err_code: 500,
          message: err.message
        })
      }
      // console.log(newUserDoc);
    })
  })

  /* 
    数据返回
  */
  if (formData.code === 0) {
    res.status(200).json({
      err_code: 0,
      message:'收藏成功'
    })
  } else if(formData.code === 1) {
    res.status(200).json({
      err_code: 0,
      message:'点赞成功'
    })
  }


}
